# -*- coding: utf-8 -*-
# author: Eduardo Cardeira
# date: 28/10/2013
# obs.: Exemplos do Livro para a Aula 6

import os
import re
import time
import sys
import urllib2
import time
import Queue
import threading
from threading import Thread

# variavel global acedida pelas threads
theVar = 1

class MyThread( threading.Thread ):
    def run (self):
        global theVar
        print 'Esta e a thread ' + str( theVar ) + ' falando.'
        print 'Ola e adeus.'
        theVar = theVar + 1

for x in xrange(20):
    MyThread().start()

#2º exemplo
# versao sequencial

lifeline = re.compile(r"(\d) received")
report = ("No response", "Partial Response", "Alive")

print time.ctime()

for host in range(10, 30):
    ip = '10.30,170.' + str(host)
    pingaling = os.popen("ping -q -c2 " + ip, "r")
    print "Testing ", ip,
    sys.stdout.flush()
    while 1:
        line = pingaling.readline()
        if not line: break
        igot = re.findall(lifeline, line)
        if igot:
            print report[int(igot[0])]

print time.ctime()

# versao com threads

class testit(Thread):
    def __init__(self, ip):
        Thread.__init__(self)
        self.ip = ip
        self.status = -1
    def run(self):
        pingaling = os.popen("ping -q -c2 "+self.ip, "r")
        while 1:
            line = pingaling.readline()
            if not line: break
            igot = re.findall(testit.lifeline, line)
            if igot:
                self.status = int(igot[0])

testit.lifeline = re.compile(r"(\d) received")
report = ("No response", "Partial Response", "Alive")

print time.ctime()

pinglist = []

for host in range(10, 30):
    ip = "10.30.170."+str(host)
    current = testit(ip)
    pinglist.append(current)
    current.start()

for pingle in pinglist:
    pingle.join()
    print "Status form ", pingle.ip, "is", report[pingle.status]

print time.ctime()


#3º exemplo
# versão sequencial

hosts = ["http://yahoo.com", "http://google.com", "http://amazon.com",
         "http://ibm.com", "http://apple.com"]

start = time.time()

#grabs urls of hosts and prints first 1024 bytes of page
for host in hosts:
    url = urllib2.urlopen(host)
    print url.read(1024)

print "Elapsed Time: %s" % (time.time() - start)

#versão com threading
hosts = ["http://yahoo.com", "http://google.com", "http://amazon.com",
         "http://ibm.com", "http://apple.com"]

queue = Queue.Queue()

class ThreadUrl(threading.Thread):
    """Threaded Url Grab"""
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self.queue = queue

    def run(self):
        while True:
            #grabs host from queue
            host = self.queue.get()

            #grabs urls of hosts and prints first 1024 bytes of page
            url = urllib2.urlopen(host)
            print url.read(1024)

            #signals to queue job is done
            self.queue.task_done()

start = time.time()

def main():

    #spawn a pool of threads and pass them queue instance
    for i in range(3):
        t = ThreadUrl(queue)
        t.setDaemon(True)
        t.start()

    #populate queue with data
    for host in hosts:
        queue.put(host)

    #wait on the queue until everything has been processed
    queue.join()

main()
print "Elaped Time: %" % (time.time() - start)


